<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <!-- <el-form-item label="产品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入产品名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="型号" prop="model">
        <el-input
          v-model="queryParams.model"
          placeholder="请输入型号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品分类" prop="categoryId">
        <el-cascader
          v-model="queryParams.categoryId"
          :options="categoryList"
          :props="props"
          clearable
          size="small"
        ></el-cascader>
        <!-- <el-select
          v-model="queryParams.categoryId"
          placeholder="请选择分类"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        >
          <el-option
            v-for="item in categoryList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select> -->
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['weixinsys:product:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['weixinsys:product:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['weixinsys:product:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['weixinsys:product:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="productList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="产品图" align="center" prop="poster"
        ><template slot-scope="scope">
          <my-image :src="scope.row.poster" preview style="width:60px;height:60px;" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="产品名称" align="center" prop="name" /> -->
      <el-table-column label="型号" align="center" prop="model" />
      <el-table-column label="产品分类" align="center" prop="categoryId">
        <template slot-scope="scope">
          <span>
            {{ formatterCategory(scope.row.categoryId) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="特点" align="center" prop="feature" />
      <el-table-column label="官网地址" align="center" prop="url">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.url"
            size="mini"
            type="text"
            @click="openUrl(scope.row.url)"
            >查看</el-button
          >
        </template>
      </el-table-column>
      <el-table-column label="视频地址" align="center" prop="videoUrl">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.videoUrl"
            size="mini"
            type="text"
            @click="openUrl(scope.row.videoUrl)"
            >预览</el-button
          >
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleUpdateFujian(scope.row)"
            v-hasPermi="['weixinsys:product:edit']"
            >附件</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['weixinsys:product:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['weixinsys:product:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改产品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="产品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入产品名称" />
        </el-form-item> -->
        <el-form-item label="型号" prop="model">
          <el-input v-model="form.model" placeholder="请输入型号" />
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-cascader
            v-if="open"
            v-model="form.categoryId"
            :options="categoryList"
            :props="props"
            clearable
            style="width:100%;"
          ></el-cascader>
          <!-- <el-select
            v-model="form.categoryId"
            placeholder="请选择分类"
            clearable
            size="small"
          >
            <el-option
              v-for="item in categoryList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select> -->
        </el-form-item>
        <el-form-item label="特点" prop="feature">
          <el-input
            v-model="form.feature"
            type="textarea"
            placeholder="请输入内容"
          />
          <span style="color:#333;font-size:12px;"
            >一条特点一行（回车换行）</span
          >
        </el-form-item>
        <el-form-item label="产品图" prop="poster">
          <ImageUpload v-model="form.poster" />
        </el-form-item>
        <el-form-item label="官网地址" prop="url">
          <el-input
            v-model="form.url"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="视频地址" prop="videoUrl">
          <ImageUpload type="2" v-model="form.videoUrl" accept="video/*" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 附件管理 -->
    <el-dialog
      title="附件管理"
      :visible.sync="fujianOpen"
      width="800px"
      append-to-body
    >
      <!-- :fileType="['pdf','pptx','docx']" -->
      <FileUpload
        :limit="0"
        :aid="form.id"
        v-if="fujianOpen"
        v-model="attachmentList"
        @success="handleUpdateFujian({ id: form.id })"
      />
      <div slot="footer" class="dialog-footer">
        <!-- <el-button type="primary" @click="submitForm">确 定</el-button> -->
        <el-button @click="cancelFujian">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listProduct,
  getProduct,
  delProduct,
  addProduct,
  updateProduct,
  exportProduct
} from "@/api/weixinsys/product";
import { listCategory } from "@/api/weixinsys/category";
import ImageUpload from "@/components/ImageUpload";
import FileUpload from "@/components/FileUpload/list";

export default {
  name: "Product",
  components: {
    ImageUpload,
    FileUpload
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品表格数据
      productList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        model: null,
        categoryId: [],
        feature: null,
        url: null,
        videoUrl: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // name: [{ required: true, message: "请输入产品名称", trigger: "blur" }],
        model: [{ required: true, message: "请输入产品型号", trigger: "blur" }],
        categoryId: [
          { required: true, message: "请选择分类", trigger: "blur" }
        ],
        poster: [{ required: true, message: "请上传产品图", trigger: "blur" }],
        feature: [{ required: true, message: "请输入特点", trigger: "blur" }]
      },
      categoryList: [],
      cList: [],
      // fujian
      fujianOpen: false,
      attachmentList: [],
      props: {
        children: "children",
        label: "name",
        value: "id",
        checkStrictly: true
      }
    };
  },
  created() {
    this.getList();
    listCategory({ pageSize: 99, pageNum: 1 }).then(res => {
      this.cList = res.rows;
      this.categoryList = this.handleTree(res.rows, "id", "pid");
    });
  },
  methods: {
    openUrl(url) {
      if (!url) {
        return;
      }
      window.open(url);
    },
    handleUpdateFujian(row) {
      const id = row.id;
      getProduct(id).then(response => {
        this.form = response.data;
        this.fujianOpen = true;
        this.attachmentList = response.data.wxSysAttachmentList.filter(
          x => !!x.fileUrl
        );
      });
    },
    cancelFujian() {
      this.reset();
      this.attachmentList = [];
      this.fujianOpen = false;
    },
    formatterCategory(val) {
      if (!this.cList.length) return "";
      let category = this.cList.find(item => item.id === val);
      return category ? category.name : "";
    },
    /** 查询产品列表 */
    getList() {
      this.loading = true;
      listProduct({
        ...this.queryParams,
        categoryId: "",
        categoryPath: this.queryParams.categoryId[
          this.queryParams.categoryId.length - 1
        ]
      }).then(response => {
        this.productList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        model: null,
        categoryId: null,
        feature: null,
        url: null,
        videoUrl: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加产品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getProduct(id).then(response => {
        if(response.data.categoryPath){
          response.data.categoryId = response.data.categoryPath
            .split(",")
            .map(Number);
        }
        this.form = response.data;
        this.open = true;
        this.title = "修改产品";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let categoryId = Array.isArray(this.form.categoryId)
            ? this.form.categoryId[this.form.categoryId.length - 1]
            : this.form.categoryId;

          let categoryPath = Array.isArray(this.form.categoryId)
            ? this.form.categoryId.join(",")
            : this.form.categoryPath.join(",");

          if (this.form.id != null) {
            updateProduct({ ...this.form, categoryId, categoryPath }).then(
              response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            );
          } else {
            addProduct({ ...this.form, categoryId, categoryPath }).then(
              response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            );
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除产品编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return delProduct(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有产品数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return exportProduct(queryParams);
        })
        .then(response => {
          this.download(response.msg);
        });
    }
  }
};
</script>
